<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>补充-手写bind函数的实现</title>
</head>
<body>

  <script>
    function foo(name, age, ...otherArgs) {
      console.log(this, name, age, ...otherArgs)
      return 111
    }
    
    // createBind 函数的实现
    Function.prototype.createBind = function(context, ...otherArgs) {
      // 如果 context 为 null 或 undefined，默认指向 globalThis
      context = context || globalThis;

      // 将函数绑定到 context 上
      context.fn = this;

      // 1. 获取context, 并且确保是一个对象类型
      context = (context === null || context === undefined) ? window : Object(context);
      // const result = context.fn(...(args || [])); // 如果 args 为 null，使用空数组

      // content.fn = this
      Object.defineProperty(context, 'fn', {
        value: this,
        writable: true, // 可写(可修改)
        configurable: true, // 可配置(可删除)
        enumerable: false // 不可枚举(for...in遍历不到)
      })

      return (...args) => {
        const allArgs = [...otherArgs, ...args];
        const res = context.fn(...allArgs);

        return res;
      }
    }

    const resBind = foo.createBind({name: "createBind"}, "bind", 18)
    console.log(resBind('bind1', 19));
    console.log(resBind('bind2', 29));
    
  </script>
  
</body>
</html>